package com.zwj.spring_study.a03;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * 模板方法模式练习
 *
 * @author 张文接
 * @version 1.0
 * @createTime 2024/5/26 20:01
 */
@Slf4j
public class TemplateMethod2 {
    public static void main(String[] args) {
        MyBeanFactory myBeanFactory = new MyBeanFactory();
        //需要进行扩展的内容
        myBeanFactory.addBeanProcessor(new BeanPostProcessor() {
            @Override
            public void postProcessBeforeInitialization(Object bean) {
                log.info("===》初始化前置方法");
            }

            @Override
            public void postProcessAfterInitialization(Object bean) {
                log.info("===》初始化后置方法");
            }
        });
        String bean = myBeanFactory.getBean(String.class);
    }

    public static class MyBeanFactory {
        //后置处理器容器
        private final List<BeanPostProcessor> processors = new ArrayList<>();

        public <T> T getBean(Class<T> tClass) {
            try {
                log.info("实例化");
                T bean = tClass.getDeclaredConstructor().newInstance();
                log.info("依赖注入");
                processors.forEach(item -> item.postProcessBeforeInitialization(bean));
                log.info("初始化");
                processors.forEach(item -> item.postProcessAfterInitialization(bean));
                return bean;
            } catch (Exception e) {
                log.error("bean初始化失败", e);
            }
            return null;
        }

        public void addBeanProcessor(BeanPostProcessor beanPostProcessor) {
            processors.add(beanPostProcessor);
        }
    }

    /**
     * bean初始化后置处理器
     */
    public interface BeanPostProcessor {
        /**
         * 初始化之前扩展
         *
         * @param bean 待扩展的类
         */
        void postProcessBeforeInitialization(Object bean);

        /**
         * 初始化之后扩展
         *
         * @param bean 待扩展的类
         */
        void postProcessAfterInitialization(Object bean);
    }
}
